#include "LuckyDrawCacheData.h"


LuckyDrawCacheData* LuckyDrawCacheData::mInstance = NULL;

void LuckyDrawCacheData::CreateInstance()
{
	if (mInstance == nullptr)
	{
		mInstance = new LuckyDrawCacheData();
	}
}

LuckyDrawCacheData* LuckyDrawCacheData::GetInstance()
{
	return mInstance;
}

LuckyDrawCacheData::LuckyDrawCacheData()
	: m_maxCount(0)
{
}

LuckyDrawCacheData::~LuckyDrawCacheData()
{
	Clear();
}

bool LuckyDrawCacheData::Reload()
{
	_safe_guard_begin;

	Clear();

	Initialization();

	_safe_guard_end;

	return false;
}

void LuckyDrawCacheData::Clear()
{
	_safe_guard_begin;

	auto itor = m_mapCacheData.begin();
	for (; itor != m_mapCacheData.end(); ++itor)
	{
		_safe_delete(itor->second);
	}

	m_mapCacheData.clear();

	_safe_guard_end;
}

bool LuckyDrawCacheData::Initialization()
{
	_safe_guard_begin;

	Json::Value _jv = ReadJsonFile("./data/activity/luckyDraw.json");
	if (_jv == Json::nullValue)
	{
		LOG_ERROR("default","ReadJsonFile -> data/activity/luckyDraw.json failed ......");
		return false;
	}

	m_maxCount = _jv.size();

	Json::Value::Members _tmp = _jv.getMemberNames();
	uint32_t _size = (uint32_t)(_tmp.size());
	for (uint32_t i = 0; i < _size; ++i)
	{
		uint32_t _idx = (uint32_t)atoi(_tmp[i].c_str());

		AddData(_idx, _jv[_tmp[i]]);
	}

	return true;

	_safe_guard_end;

	return false;
}


void LuckyDrawCacheData::AddData(uint32_t id, Json::Value& jm)
{
	_safe_guard_begin;

	auto itor = m_mapCacheData.find(id);
	if (itor == m_mapCacheData.end())
	{
		LuckyDraw* p = new LuckyDraw;
		_safe_check(p);

		p->mId = jm["id"].asUInt();
		p->mDiamondCost = jm["diamond_cost"].asUInt();
		p->mBasicRate = jm["basic_rate"].asUInt();
		p->mCommonDifference = jm["common_difference"].asUInt();
		p->mMidas2 = jm["midas2"].asUInt();
		p->mMidas5 = jm["midas5"].asUInt();
		p->mMidas10 = jm["midas10"].asUInt();

		m_mapCacheData[id] = p;
	}

	_safe_guard_end;
}


LuckyDraw* LuckyDrawCacheData::GetData(uint32_t id)
{
	_safe_guard_begin;

	auto itor = m_mapCacheData.find(id);
	if (itor != m_mapCacheData.end())
	{
		return itor->second;
	}
	_safe_guard_end;

	return nullptr;
}

bool LuckyDrawCacheData::GetDataJsonString(uint32_t id, Json::Value& _jm)
{
	_safe_guard_begin;

	LuckyDraw* p = GetData(id);
	if (nullptr == p)
	{
		LOG_ERROR("default","Error9");
		return false;
	}

	_jm.clear();

	_jm["id"] = Json::Value(p->mId);
	_jm["diamond_cost"] = Json::Value(p->mDiamondCost);
	_jm["basic_rate"] = Json::Value(p->mBasicRate);
	_jm["common_difference"] = Json::Value(p->mCommonDifference);
	_jm["midas2"] = Json::Value(p->mMidas2);
	_jm["midas5"] = Json::Value(p->mMidas5);
	_jm["midas10"] = Json::Value(p->mMidas10);

	_safe_guard_end;

	return true;
}

uint32_t LuckyDrawCacheData::GetDataCount()
{
	_safe_guard_begin;

	return m_maxCount;

	_safe_guard_end;
}

